<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	    <script type="text/javascript" src="tgd/Services/Google/Search.js"></script>
		<script type="text/javascript" src="tgd/Media/MediaLibrary.js"></script>
		<script type="text/javascript" src="tgd/Media/Library.js"></script>
		<script type="text/javascript" src="tgd/Media/Entry.js"></script>
		<title>Media Library</title>
		<script type="text/javascript">
			//<![CDATA[

var medlib;

function init() {
    medlib = new tgd.Media.MediaLibrary(
        function(msg) {
            if (msg.Status === 1) {
                medlib.setGoogleCallback(callbackWithGoogleData);
                loadLibraries();
                loadUncategorizedEntries();
            } else {
                alert(msg.Message);
            }
        }
    );
}

function setTitleForUPC(title, upc, source) {
    var entry = medlib.getEntryByUPC(upc);

    entry.setName(title);
    entry.setNameSource(source);
    entry.Element.getElementsByClassName("txtTitle")[0].value = title;
    entry.Element.getElementsByClassName("lblTitleSource")[0].textContent = source;
    entry.Element.scrollIntoView();
    entry.Element.getElementsByClassName("resultsToSave")[0].style.display = "";
}

function setThumbForUPC(url, source, upc, img) {
    //todo: possibly add a GUI object onto the entry. i.e. entry.GUI.ImageThumbnail, entry.GUI.TitleRepeater, etc.
    var entry = medlib.getEntryByUPC(upc);
    
    entry.setThumbURL(url);
    entry.Element.getElementsByClassName("imgThumb")[0].src = url;
    entry.Element.getElementsByClassName("lblThumbSource")[0].textContent = source;
    entry.Element.getElementsByClassName("height")[0].textContent = img.naturalHeight;
    entry.Element.getElementsByClassName("width")[0].textContent = img.naturalWidth;
    entry.Element.scrollIntoView();
    entry.Element.getElementsByClassName("resultsToSave")[0].style.display = "";
}

//load the libraries to the template drop down list
function loadLibraries() {
    var ddlTemplate = document.getElementById("templateRow").getElementsByClassName("ddlLibraries")[0];
    var libs = medlib.getLibraries();
    
    for (var i = 0; i < libs.length; ++i) {
        var lib = libs[i];
        var o = document.createElement("option");
        o.label = lib.getName();
        o.value = lib.getID();
        o.selected = o.value == medlib.getCurrentLibrary().getID();
        ddlTemplate.options.add(o);
    }
}

function loadUncategorizedEntries() {
    var libs = medlib.getLibraries();
    
    for (var i = 0; i < libs.length; ++i) {
        var lib = libs[i];
        var ents = lib.getEntries();
        
        for (var j = 0; j < ents.length; ++j) {
            var entry = ents[j];
            if (entry.getName() === "") {  //"uncategorized"
                createEntryRow(lib, entry);
            }
        }
    }
}

function createEntryRow(library, entry) {
    var r = document.getElementById("upcRepeater");

    var divContainer = entry.Element = document.getElementById("templateRow").cloneNode(true);
    divContainer.id = "";

    var divHeader = divContainer.getElementsByClassName("rowHeader")[0];
    var ddlLibraries = divContainer.getElementsByClassName("ddlLibraries")[0];
    var lblUPC = divContainer.getElementsByClassName("lblUPC")[0];
    var btnSave = divContainer.getElementsByClassName("btnSave")[0];
    var lblLibName = divContainer.getElementsByClassName("lblLibName")[0];
    var lblEntUPC = divContainer.getElementsByClassName("lblEntUPC")[0];
    var btnShowData = divContainer.getElementsByClassName("btnShowData")[0];
    var btnHideData = divContainer.getElementsByClassName("btnHideData")[0];

    for (var j = 0; j < ddlLibraries.options.length; ++j) {
        if (ddlLibraries.options[j].value === library.getID()) {
            ddlLibraries.options[j].selected = true;
            break;
        }
    }

    lblUPC.textContent = entry.getUPC();
    btnSave.title = entry.getUPC();
    lblLibName.textContent = library.getName()
    lblEntUPC.textContent = entry.getUPC();
    
    btnShowData.title = entry.getUPC();
    btnShowData.onclick = function(event) {
        //TODO:  if we already got data from google, then don't load again, maybe do something else.
        event.target.style.display = "none";
        event.target.parentNode.getElementsByClassName("panLoading")[0].style.display = "block";
        event.target.parentNode.getElementsByClassName("btnHideData")[0].style.display = "inline";
        event.target.parentNode.parentNode.getElementsByClassName("dataContainer")[0].style.display = "block";

        medlib.getGoogleData(event.target.title, callbackWithGoogleData);
    }

    btnHideData.onclick = function(event) {
        event.target.style.display = "none";
        event.target.parentNode.getElementsByClassName("btnShowData")[0].style.display = "inline";
        event.target.parentNode.parentNode.getElementsByClassName("dataContainer")[0].style.display = "none";
    }

    r.appendChild(divContainer);
}

/*
 * src = { URL, Source }
 */
function addImage(src, containerElement, upc) {
	var template = document.getElementById("templateImage");

	var imgContainer = template.cloneNode(true);
	imgContainer.id = "";

	var loadingImages = containerElement.getElementsByClassName("loading")[0];
	var loadedImages = containerElement.getElementsByClassName("thumbResults")[0];
	var img = imgContainer.getElementsByClassName("imgThumb")[0];

	imgContainer.Thumb = { 
		Height : imgContainer.getElementsByClassName("height")[0],
		Width: imgContainer.getElementsByClassName("width")[0]
	};
	
	img.onerror = function(event) {
	    //TODO: remove this image from the results, don't want it again.
	    //todo: decrement # of loading images
	}
	
	img.onload = function(event) {
	    //todo: decrement # of loading images
		var currentImage = event.target;
		var imageContainer = currentImage.parentNode;
		var insertBeforeImageContainer = null;

		imageContainer.style.display = "block";
		imageContainer.Thumb.Area =
			(imageContainer.Thumb.Width.textContent = currentImage.naturalWidth) *
			(imageContainer.Thumb.Height.textContent = currentImage.naturalHeight);

		for (var i = 0, nextImageContainer = loadedImages.childNodes[i]; i < loadedImages.childNodes.length; nextImageContainer = loadedImages.childNodes[++i]) {
			if (imageContainer.Thumb.Area <= nextImageContainer.Thumb.Area) {
				insertBeforeImageContainer = nextImageContainer;
				break;
			}
		}

		loadedImages.insertBefore(imageContainer, insertBeforeImageContainer);
	}

    img.onclick = function(event) {
	    event.target.parentNode.parentNode.style.display = 'none';
        setThumbForUPC(event.target.src, event.target.Source, event.target.title, event.target);
    }

    img.title = upc;
	img.src = src.URL;
	img.Source = src.Source;
	loadingImages.appendChild(imgContainer);
}

function saveDataForUPC(upc) {
    var entry = medlib.getEntryByUPC(upc);

    entry.save(
        function(msg) {
            if (msg.Status === 1) {
                msg.Entry.Element.style.display = "none";
            } else {
                //todo: what can i do?
            }
            alert(msg.Message);
        }
    );
}

function cancelEdit(rowContainer) {
    rowContainer.getElementsByClassName("dataContainer")[0].style.display = "none";
    rowContainer.getElementsByClassName("btnShowData")[0].style.display = "inline";
    rowContainer.getElementsByClassName("btnHideData")[0].style.display = "none";
}

function loadAll() {
    var r = document.getElementById("upcRepeater");
    for (var i = 0; i < r.childNodes.length; ++i) {
        var h = r.childNodes[i].getElementsByClassName("rowHeader")[0];
        tgd.Services.Google.Search.getUPC(h.title);
    }
}

function titleEdit(btn) {
    btn.parentNode.parentNode.parentNode.getElementsByClassName("titleResults")[0].style.display = "";
}

function titleClean(btn) {
    var txtTitle =  btn.parentNode.getElementsByClassName("txtTitle")[0];
    var title = txtTitle.value;
    var firstParenIndex;
    if ((firstParenIndex = title.indexOf("(")) > 0) {
        txtTitle.value = title.substr(0, firstParenIndex - 1);
    }
}

function titleCamel(btn) {
    var txtTitle =  btn.parentNode.getElementsByClassName("txtTitle")[0];
    var title = txtTitle.value;
    var words = title.split(' ');
    
    for (var i = 0; i < words.length; ++i) {
        words[i] = words[i].toLowerCase().replace(/^\w/, words[i].charAt(0).toUpperCase());
    }    

    txtTitle.value = words.join(' ');
}

function thumbEdit(btn) {
    btn.parentNode.parentNode.parentNode.getElementsByClassName("thumbResults")[0].style.display = "";
}

function callbackWithGoogleData(entry) {
    var current = entry;  //TODO: remove current, use entry
    var results = entry.getGoogleData();
    var titleResults = current.Element.getElementsByClassName("titleResults")[0];
    titleResults.textContent = "";
    entry.Element.getElementsByClassName("panLoading")[0].style.display = "none";
    
    for (var i = 0; i < results.Title.length; ++i) {
        var div = document.createElement("div");
        div.title = current.getUPC();
        div.textContent = results.Title[i].Name;
        div.NameSource = results.Title[i].Source;
        div.onclick = function() {
		    this.parentNode.style.display = 'none';
            setTitleForUPC(this.textContent, this.title, this.NameSource);
        }
        titleResults.appendChild(div);

    }
    
    var thumbResults = current.Element.getElementsByClassName("thumbResults")[0];
    thumbResults.textContent = "";
    
    for (var i = 0; i < results.Thumb.length; ++i) {
        addImage(results.Thumb[i], current.Element, current.getUPC());
    }
}

			//]]>
		</script>

		<style type="text/css">
			body,html{margin:0;height:100%;width:100%;background:#1C1C1C;font-family:sans-serif;}

			#menu{color:#666;}
			#menu a{text-decoration:none;padding:0 10px;margin:0 10px;color:#666;}
			#menu a.current{background:#a4c639;color:#333;}

			#modeEnter{background:#333;}
			#modeEnter h1{background:#a4c639;color:#333;padding:7px 0;margin:0;text-align:center;position:relative;font-size:1em;}
			/*#modeEnter ul{padding:0;margin:0;}
			#modeEnter li{padding:.2em;}*/
			#modeEnter #upcRepeater .rowContainer{color:#ccc;border-bottom:solid 1px #a4c639;position:relative;}
            #modeEnter #upcRepeater .rowContainer .rowHeader{background:#1f1f1f;border-top:solid 1px #000;padding:10px 0;}
            #modeEnter #upcRepeater .rowContainer .resultsToSave{background:#555;border-top:solid 1px #808080;padding:10px 0;}
            #modeEnter #upcRepeater .rowContainer .resultsToSave div{padding:10px 0;}
            #modeEnter #upcRepeater .rowContainer .titleResults div{border-top:solid 1px #808080;padding:10px 0;}
            #modeEnter #upcRepeater .rowContainer .thumbResults{border-top:solid 1px #808080;}

            .resultsToSave{}
            .resultsToSave a {text-decoration:none;color:#333;padding:5px 15px;border:solid 1px #7EA600;background:#C1DE68;}

			.img{display:none;float:left;padding:5px;color:#666;text-align:center;font-size:10pt;background:#333;-moz-border-radius:5px;border:solid 1px #666;margin:10px;}
			.img img{height:75px;}
			.loading{clear:both;}
            
            .panLoading{display:none;background:#000;opacity:0.8;padding:10px;text-align:center;vertical-align:middle;position:absolute;top:0;right:0;bottom:0;left:0;}
            
            #template,#templates{display:none;}
    	</style>
	</head>
	<body id="body" onload="init();">
		<div id="menu">
			<a href="Biblio1.htm">Scan</a>
			<a href="Biblio2.htm" class="current">Uncatagorized</a>
			<a href="Biblio3.htm">My Library</a>
		</div>
		<div id="content">
			<div id="modeEnter">
			    <h1>
			        <input type="button" value="Load All" onclick="loadAll();" />
			    </h1>
			    <div id="upcRepeater"></div>
			</div>
		</div>
		<div id="templates">
		    <div id="templateImage" class="img">
			    <img class="imgThumb" />
			    <br />
			    <span class="width"></span> x <span class="height"></span>
		    </div>
	        <div class="rowContainer" id="templateRow">
	            <div class="rowHeader">
	                <span class="lblLibName"></span>
	                &mdash;
	                <span class="lblEntUPC"></span>
	                <input type="button" class="btnHideData" value="-" style="display:none;" />
	                <input type="button" class="btnShowData" value="+" />
                    <div class="panLoading">loading &#8230;</div>
	            </div>
	            <div class="dataContainer">
	                <div class="resultsToSave" style="display:none;">
	                    <div>Data to save for UPC [<span class="lblUPC"></span>]:</div>
	                    <div>Library:
		                    <select class="ddlLibraries">
		                    </select>
	                    </div>
	                    <div>
                            Title:
                            <input type="text" class="txtTitle" size="20" />
                            <br />
                            Source:
                            <span class="lblTitleSource"></span>
                            <br />
                            <input type="button" class="button btnCamelTitle" value="Camel" onclick="titleCamel(this);" />
                            <input type="button" class="button btnCleanTitle" value="Clean" onclick="titleClean(this);" />
                            <input type="button" class="button btnEditTitle" value="Edit" onclick="titleEdit(this);" />
                            </div>
                        <div>
                            Thumbnail: EDIT URL?
                            <br />
                            Source:
                            <span class="lblThumbSource"></span>
                            <br />
                            Dimensions: <span class="width"></span> x <span class="height"></span>
                            <br />
                            <img class="imgThumb" alt="." />
                            <br />
                            <input type="button" class="button btnEditThumb" value="Edit" onclick="thumbEdit(this);" />
                        </div>
	                    <div>
	                        <input type="button" class="button btnSave" onclick="saveDataForUPC(this.title);" value="Save" />
	                        <input type="button" class="button btnCancel" onclick="cancelEdit(this.parentNode.parentNode.parentNode.parentNode);" value="Cancel" />
	                    </div>
	                </div>
	                <div class="titleResults"></div>
	                <div class="thumbResults"</div>
		            <div class="loading"></div>
	            </div>
	        </div>
	    </div>
	</body>
</html>
